package com.hk.service.business;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hk.service.demo.UserService;
import com.hk.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import com.hk.domain.entity.User;
import org.springframework.transaction.TransactionStatus;

import java.util.List;


@Service
public class UserBusiness {

    // 需要先注入如下两个类
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private UserService userService;


    /**
     * 事务分类：
     * 1、声明式事务[@Transactional(rollbackFor = Exception.class)]
     *    >利用AOP的思想，有时候可以会因为各种问题会导致事务失效
     * 2、编程式事务[手动控制 commit、rollback]，粒度更细一点
     *    >手动操作jdbc的事务：适用于有多条SQL操作时，保障全部成功或者全部失败
     */
    public R manualCommitTransaction() {
        //开启事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            User user = new User();
            user.setUsername("zs");
            user.setPassword("1234");
            userService.save(user);
            //
            int i  = 5/0;
            dataSourceTransactionManager.commit(transaction);
        } catch (Exception e) {
            dataSourceTransactionManager.rollback(transaction);
        }
        return R.ok();
    }

    public IPage page(Page page) {
        IPage iPage = userService.page(page, new LambdaQueryWrapper<>());
        return iPage;
    }
}
